package com.ukee.birthday.modules.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ukee.birthday.common.utils.R;
import com.ukee.birthday.modules.dao.SysUserTokenDao;
import com.ukee.birthday.modules.entity.SysUserTokenEntity;
import com.ukee.birthday.modules.oauth2.TokenGenerator;
import com.ukee.birthday.modules.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {

    //7天后过期
//    private final static int EXPIRE = 3600*24*7;
    //一年后过期
    private final static int EXPIRE = 3600*24*365;
    @Override
    public R createToken(long userId,int type) {

        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE*1000);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = this.getById(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setType(type);

            //保存token
            this.save(tokenEntity);
            R r = R.ok().put("token",token).put("expire",EXPIRE);
            return r;

        }else {
//            tokenEntity.setToken(token);
//            tokenEntity.setExpireTime(expireTime);
//            tokenEntity.setUpdateTime(now);
//            tokenEntity.setType(type);
//            //更新token
//            this.updateById(tokenEntity);

            //登录相同平台，更新token
            if( tokenEntity.getType() == type){
                tokenEntity.setToken(token);
                tokenEntity.setExpireTime(expireTime);
                tokenEntity.setUpdateTime(now);
                tokenEntity.setType(type);
                //更新token
                this.updateById(tokenEntity);
            }else {
                //不同平台，拿到token，延长过期时间
                tokenEntity.setExpireTime(expireTime);
                tokenEntity.setUpdateTime(now);
                tokenEntity.setType(type);
                //更新token
                this.updateById(tokenEntity);
            }
            R r = R.ok().put("token",tokenEntity.getToken()).put("expire",EXPIRE);
            return r;
        }

//        R r = R.ok().put("token",token).put("expire",EXPIRE);
//        return r;
    }

    @Override
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        tokenEntity.setToken(token);
        tokenEntity.setUserId(userId);
        this.updateById(tokenEntity);
    }
}
